package com.aglow.updateDownload.code;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import com.aglow.updateDownload.listener.UpdateDownloadListener;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DecimalFormat;


/**
 * Author: chufeng
 * Email: 392044178@qq.com
 * Date: 2019/1/3 15:44
 * Depict:下载请求模块
 */
public class UpdateDownloadRequest implements Runnable {

    private final DownloadResponseHandle downloadResponseHandler;
    private String downloadUrl;
    private String localFilePath;
    private UpdateDownloadListener listener;
    private boolean isDownloading = false;
    private int currentLength;

    public UpdateDownloadRequest(String url, String localFilePath, UpdateDownloadListener listener) {
        this.downloadUrl = url;
        this.localFilePath = localFilePath;
        this.listener = listener;
        this.isDownloading = true;
        downloadResponseHandler = new DownloadResponseHandle();
    }

    @Override
    public void run() {
        try {
            makeRequest();
        } catch (Exception e) {

        }

    }

    private void makeRequest() throws IOException, InterruptedIOException {
        if (!Thread.currentThread().isInterrupted()) {
            try {
                URL url = new URL(downloadUrl);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.setReadTimeout(5000);
                connection.setConnectTimeout(5000);
                connection.setRequestProperty("Connection", "Keep-Alive");
                connection.connect();
                currentLength = connection.getContentLength();
                Log.i("update","请求的数据包大小 = "+currentLength);
                if (!Thread.currentThread().isInterrupted()) {
                    downloadResponseHandler.sendResponseMessage(connection.getInputStream());
                }
            } catch (Exception e) {
                throw e;
            }
        }


    }

    private class DownloadResponseHandle {
        /**
         * 状态常量
         **/
        protected static final int SUCCESS_MESSAGE = 0;
        protected static final int FAILURE_MESSAGE = 1;
        protected static final int START_MESSAGE = 2;
        protected static final int FINISH_MESSAGE = 3;
        protected static final int NETWORK_OFF = 4;
        private static final int PROGRESS_CHANGED = 5;

        private Handler handler;

        private float completeSize = 0;
        private int progress = 0;

        @SuppressLint("HandlerLeak")
        public DownloadResponseHandle() {
            handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    handleSelfMessage(msg);
                }
            };

        }

        /**
         * 处理消息回调给应用层
         *
         * @param msg
         */
        protected void handleSelfMessage(Message msg) {

            switch (msg.what) {
                case FAILURE_MESSAGE:
                    handleFailureMessage();
                    break;
                case PROGRESS_CHANGED:
                    handleProgressChangedMessage(msg.arg1);
                    break;
                case FINISH_MESSAGE:
                    onFinish();
                    break;
            }

        }
        //------------------------------------------------------

        /**
         * 下載完成
         */
        private void onFinish() {
            if (listener != null) {
                listener.onFinished(completeSize, downloadUrl);
            }
        }

        protected void sendFinishMessage() {
            sendMessage(obtainMessage(FINISH_MESSAGE, 100));
        }
        //------------------------------------------------------

        /**
         * 發送失敗
         */
        private void sendFailureMessage() {
            sendMessage(obtainMessage(FAILURE_MESSAGE, -1));
        }

        private void handleFailureMessage() {
            if (listener != null) {
                listener.onFailure();
            }
        }


        //------------------------------------------------------

        /**
         * 進度變化
         *
         * @param progress
         */
        private void handleProgressChangedMessage(int progress) {
            listener.onProgressChanged(progress, downloadUrl);
        }

        private void sendProgressChangedMessage(int progress) {
            sendMessage(obtainMessage(PROGRESS_CHANGED, progress));
        }
        //------------------------------------------------------

        protected void sendMessage(Message msg) {
            if (handler != null) {
                handler.sendMessage(msg);
            } else {
                handleSelfMessage(msg);
            }

        }

        protected Message obtainMessage(int responseMessge, int progress) {
            Message msg = null;
            if (handler != null) {
                msg = handler.obtainMessage(responseMessge, progress);
            } else {
                msg = Message.obtain();
                msg.what = responseMessge;
                msg.arg1 = progress;


            }
            return msg;
        }

        private String getTwoPointFloatStr(float value) {
            DecimalFormat df = new DecimalFormat("0.00000000000");
            return df.format(value);
        }

        /**
         * 发送请求 开始下载
         *
         * @param is
         */
        public void sendResponseMessage(InputStream is) {
            RandomAccessFile rf = null;
            completeSize = 0;
            try {
                byte[] buffer = new byte[1024];
                int length = -1;
                int limit = 1; //限制進度條上報速度
                rf = new RandomAccessFile(localFilePath, "rwd");
                while ((length = is.read(buffer)) != -1) {
                    if (isDownloading) {
                        rf.write(buffer, 0, length);
                        completeSize += length;
                        progress =  (int)(Float.parseFloat(getTwoPointFloatStr(completeSize/currentLength))*100);
                        Log.i("update", "progress = " + progress+" "+"completeSize = "+completeSize+" "+"currentLength = "+currentLength);
                        if (limit % 60 == 0 && progress <= 100) {
                            sendProgressChangedMessage(progress);

                        }
                        limit++;
                    }
                }
                sendFinishMessage();//下载完成
            } catch (IOException e) {
                e.printStackTrace();
                sendFailureMessage();
                Log.i("update", "下载失败");
            } finally {
                try {
                    if (is != null) {
                        is.close();
                    } if(rf!=null){
                        rf.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    sendFailureMessage();
                    Log.i("update", "流关闭失败");
                }
            }


        }
    }
}
